/*Copyright (C) 2009 Careil Baptiste

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/

#include <stdlib.h>
#include <string.h>

#include "Dames_destination.h"
#include "Dames_constantes.h"
#include "../types/types.h"

void Dames_AddDest(DAMES_CASEVALUE array[DAMES_ARRAY_SIZE][DAMES_ARRAY_SIZE], DAMES_POS *pos, IPoint newDest) {
	IPoint *destTemp = NULL;
	unsigned int newDestLen = pos->destLen + 1;

	if(pos->dest != NULL) {
		destTemp = malloc(pos->destLen * sizeof(IPoint));
		memcpy(destTemp, pos->dest, pos->destLen);
		free(pos->dest);
	}

	//allocation du nouveau tableau de destination
	pos->dest = malloc(newDestLen * sizeof(IPoint));

	if(destTemp != NULL) {
		memcpy(pos->dest, destTemp, pos->destLen);
	}
	//ajout de la nouvelle destination
	pos->dest[newDestLen-1] = newDest;
	pos->destLen = newDestLen;
	Dames_Ajouter(array, DEST, newDest);

	//libération de la mémoire
	free(destTemp);
}

void Dames_RemDest(DAMES_CASEVALUE array[DAMES_ARRAY_SIZE][DAMES_ARRAY_SIZE], DAMES_POS *pos, IPoint remDest) {
	int i = 0, j = 0, newDestLen = pos->destLen - 1;
	IPoint *destTemp = malloc(pos->destLen * sizeof(IPoint));

	if(pos->dest == NULL)
		return;

	memcpy(destTemp, pos->dest, pos->destLen);
	free(pos->dest);
	pos->dest = malloc(newDestLen * sizeof(IPoint));
	while(i < newDestLen) {
		if(destTemp[j].x != remDest.x && destTemp[j].y != remDest.y) {
			pos->dest[i] = destTemp[j];
			i++;
		}
		j++;
	}
	Dames_Enlever(array, DEST, remDest);
	free(destTemp);
	pos->destLen = newDestLen;
	if(pos->destLen == 0)
		pos->dest = NULL;
}

void Dames_ClearDest(DAMES_CASEVALUE array[DAMES_ARRAY_SIZE][DAMES_ARRAY_SIZE], DAMES_POS *pos) {
	unsigned int i;
	for(i = 0; i < pos->destLen; i++) {
		Dames_Enlever(array, DEST, pos->dest[i]);
	}
	if(pos->dest)
		free(pos->dest);
	pos->dest = NULL;
	pos->destLen = 0;
}

